import moment from "moment";
import html2canvas from "html2canvas";
import { listUser, agentUser, getdeptIdUser } from "@/api/system/user";
import jsPDF from "jspdf";
/**
 * setStorage 存储
 * getStorage 取到
 * removeStorage 移除
 */
export const storage = {
  setStorage: (name, val) => {
    try {
      const obj = JSON.stringify(val);
      sessionStorage.setItem(name, obj);
    } catch (e) {
      sessionStorage.setItem(name, val);
    }
  },

  getStorage: (val) => {
    let str = sessionStorage.getItem(val);
    if (str) {
      try {
        const obj = JSON.parse(str);
        return obj;
      } catch (e) {
        return str;
      }
    } else {
      return null;
    }
  },
  removeStorage: (val) => {
    sessionStorage.removeItem(val);
  },
};

/**
 * vue 挂载
 * this...
 */

export default {
  install: function (Vue, options) {
    /**
     * 消息通知
     * mssage 信息
     */
    Vue.prototype.Notification = function (title = "提示", message, position) {
      this.$notify({
        title: title,
        message: message,
        position: position && position,
      });
    };

    /**
     * 消息提示
     * mssage 信息
     * type 图标展示类型
     */
    Vue.prototype.Message = function (message, type = "success") {
      this.$message({
        type: type,
        message: message,
      });
    };

    /**
     * 弹出窗
     * callback 返回函数
     *
     */

    Vue.prototype.MessageBox = function (
      title = "提示",
      message,
      type = "info",
      callback
    ) {
      this.$alert(message, title, {
        confirmButtonText: "确定",
        type: type,
        callback: (action) => {
          if (callback && action === "confirm") {
            callback();
          }
        },
      });
    };

    /**
     * 移除空格
     * 字符串
     *
     */

    Vue.prototype.RemoveG = function (value) {
      return value.replace(/\s*/g, "");
    };

    /**
     *  搜索重置
     */
    Vue.prototype.SearchReload = function (orgCode) {
      if (this.pagination) {
        this.pagination.page = 1;
      }
      if (this.searchData) {
        this.searchData.forEach((item) => {
          if (item.value) {
            item.value = "";
          }
        });
      }
      this.getLoad();
    };

    /**
     * 屏蔽手机号中间4位
     * 字符串
     *
     */

    Vue.prototype.GeTel = function (value) {
      const reg = /^(\d{3})\d{4}(\d{4})$/;
      return value ? value.replace(reg, "$1****$2") : "";
    };

    /**
     * 验证数组是否重复
     * 字符串
     *
     */

    Vue.prototype.IsRepeat = function (array) {
      var hash = {};
      for (var i in array) {
        if (hash[array[i]]) {
          return true;
        }
        // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
        hash[array[i]] = true;
      }
      return false;
    };

    /**
     * 获取img里src值
     * 字符串
     *
     */

    Vue.prototype.GetImgSrc = function (value) {
      var eleTmp = document.createElement("div");
      eleTmp.innerHTML = value;
      var imgSrc = objE.childNodes[0].src;
      eleTmp.remove();
      return imgSrc;
    };
    /**
     * 返回上一页
     * -1,-2,-3
     *
     */
    Vue.prototype.Back = function () {
      this.$router.back(-1);
    };

    /**
     * 格式化时间
     *
     */
    Vue.prototype.Moment = function (vaule) {
      if (vaule) {
        return moment(vaule).format("YYYY-MM-DD HH:mm:ss");
      }
      return "";
    };

    /**
     * 打开新窗口
     * （全部）
     */
    Vue.prototype.OpenRoutes = function (path = "/", query = {}) {
      let routeOne = this.$router.resolve({
        path: path,
        query: query,
      });
      window.open(routeOne.href, "_blank");
    };

    /**
     * 更新编辑数据
     * obj 列表每行数据
     * arry 表单数组
     * disabled 表单状态是否可以更改
     */
    Vue.prototype.UpdataForm = function (obj, arry, disabled = false) {
      arry.forEach((item) => {
        if (Object.keys(obj).includes(item.prop)) {
          if (disabled) {
            item.value = obj[item.prop];
            item.disabled = true;
            item.placeholder = "";
          } else {
            item.value = obj[item.prop];
          }
        }
      });
      return arry;
    };

    /**
     * 更新搜索内容
     * arry 表单数组
     * keys 日期更改数据索引值
     * tree 产品线树状结构重新赋值
     */
    Vue.prototype.UpDataObj = function (arry) {
      let obj = {};
      if (arry && arry.length > 0) {
        arry.forEach((item) => {
          obj[item.prop] = item.value;
        });
      }

      return obj;
    };

    /**
     *  表单重置
     */
    Vue.prototype.FormReload = function () {
      if (this.formData) {
        this.formData.forEach((item) => {
          item.value = "";
          item.disabled = false;
        });
      }
    };

    /**
     *  分页重置
     */
    Vue.prototype.PageReload = function () {
      this.tableData = [];
      if (this.pagination) {
        this.pagination.total = 0;
        this.pagination.page = 1;
      }
    };

    /**
     * 获取所有用户列表
     * callback 回调
     */
    Vue.prototype.GetUserList = function (callback) {
      const userList = storage.getStorage("userList");
      // if (userList) {
      //   callback(userList);
      //   return;
      // }
      // listUser({ pageNum: 1, pageSize: 1000 }).then((response) => {
      //   storage.setStorage("userList", response.rows);
      //   let data = response.rows || [];
      //   callback(data);
      // });

      agentUser({}).then((response) => {
        storage.setStorage("userList", response.data);
        let data = response.data || [];
        callback(data);
      });
    };

    /**
     * 获取审核用户列表
     * callback 回调
     */
    Vue.prototype.GetAuditUserList = function (callback) {
      const auditUserList = storage.getStorage("auditUserList");
      getdeptIdUser({}).then((response) => {
        storage.setStorage("auditUserList", response.data);
        let data = response.data || [];
        callback(data);
      });
    };

    /**
     * 打开新窗口
     * （全部）
     */
    Vue.prototype.OpenRoutes = function (path = "/", query = {}) {
      let routeOne = this.$router.resolve({
        path: path,
        query: query,
      });
      window.open(routeOne.href, "_blank");
    };

    /**
     * 生成pdf
     * （全部）
     */
    Vue.prototype.PrintPDF = async function (name, that, key) {
      //  console.log(htmlDocx);
      const content = key
        ? document.getElementById(key)
        : that.$refs.pdfContent;
      console.log(content);
      let domHeight = content.offsetHeight;
      let maxHeight = 64257;
      html2canvas(content, {
        useCORS: true, // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
        scale: maxHeight / domHeight > 1 ? 1 : maxHeight / domHeight,
      }).then((canvas) => {
        const contentWidth = canvas.width;
        const contentHeight = canvas.height;
        let pageHeight = (contentWidth / 592.28) * 841.89;
        let leftHeight = contentHeight;
        //页面偏移
        var position = 0;
        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        var imgWidth = 595.28; // A4 宽度
        var imgHeight = (592.28 / contentWidth) * contentHeight; // A4总高度
        var pageData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new jsPDF("", "pt", "a4");
        //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          pdf.addImage(pageData, "JPEG", 10, 0, imgWidth - 20, imgHeight);
        } else {
          while (leftHeight > 0) {
            pdf.addImage(
              pageData,
              "JPEG",
              10,
              position,
              imgWidth - 20,
              imgHeight
            );
            leftHeight -= pageHeight;
            position -= 841.89;
            //避免添加空白页
            if (leftHeight > 0) {
              pdf.addPage();
            }
          }
        }
        pdf.save(`${name}.pdf`);
      });

      // const canvas = await html2canvas(content);
      // const imgData = canvas.toDataURL("image/png");

      // const pdf = new jsPDF({
      //   orientation: "portrait",
      //   unit: "px",
      //   format: "a4",
      // });

      // const imgProps = pdf.getImageProperties(imgData);
      // const pdfWidth = pdf.internal.pageSize.getWidth();
      // const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
      // pdf.addImage(imgData, "PNG", 0, 0, pdfWidth, pdfHeight);
      // pdf.save(`${name}.pdf`);
    };
  },
};
